﻿using System;
using System.IO;
using System.Web.UI.WebControls;
using Contacts.Data.Data;

namespace Contacts.Web
{
    public partial class GroupList : BasePage
    {
       private readonly ContactsDataGroups _contactsDataGroups = new ContactsDataGroups();
       private readonly ContactsDataPersons _contactsDataPersons = new ContactsDataPersons();


       protected override void PageLoad()
       {
          if (!IsPostBack)
          {
             ReShowGroupList();
          }
       }

        public void ReShowGroupList()
        {
            groupsView.DataSource = _contactsDataGroups.LoadAllGroups();
            groupsView.DataBind();
        }

       public void groupsView_OnRowCommand(object sender, GridViewCommandEventArgs e)
       {

          //TODO Проверка пути иконкы:
          string i = e.CommandArgument.ToString();
          int resultInt;
          if (int.TryParse(i, out resultInt)) return;
          if (i == "Next") return;
          if (i == "Prev") return;
          if (i == "First") return;
          if (i == "Last") return;

          string[] splitArgs = e.CommandArgument.ToString().Split('|');
          string groupID = splitArgs[0];
          string iconName = splitArgs[1];


          string commandName = e.CommandName;

          if (commandName == "DeleteCmd")
          {
             int result = _contactsDataPersons.CountOfPersons(groupID);
             if (result == 0)
             {
                if (iconName != "DefaultIcon.png")
                {
                   File.Delete("C:\\Images\\" + iconName);
                }
                _contactsDataGroups.DeleteGroup(Convert.ToInt32(groupID));
             }
             else
             {
                lblWarning.Text = ": WARNING! - СНАЧАЛА УДАЛИТЕ ВСЕХ ЮЗВЕРЕЙ ЭТОЙ ГРУППЫ!";
             }

              ReShowGroupList();

          }
            else
            {
               if (commandName == "EditCmd")
               {
                  Response.Redirect("GroupEditor.aspx?GroupID=" + groupID);
               }

            }
       }

       protected void groupsView_PageIndexChanging(object sender, GridViewPageEventArgs e)
       {
          if (e.NewPageIndex < 0)
          {
             ReShowGroupList();
          }
          else
          {
             groupsView.PageIndex = e.NewPageIndex;
             ReShowGroupList();
          }
       }



    }
    }